import { useState, useEffect } from 'react'
import { Card, Button, Modal, Form, Input, Upload, message, Tabs } from 'antd'
import { PlusOutlined, UploadOutlined, UserOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import FamilyTreeView from '../components/family/FamilyTreeView'
import FamilyMemberForm from '../components/family/FamilyMemberForm'
import { useFamilyStore } from '../store/family'
import { useAuthStore } from '../store/auth'

export default function FamilyTree() {
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [currentMember, setCurrentMember] = useState<any>(null)
  const [currentTab, setCurrentTab] = useState('tree')
  
  const { 
    members, 
    trees, 
    currentTree, 
    treeStructure, 
    loading, 
    fetchMembers, 
    fetchTrees, 
    fetchTreeStructure, 
    createMember, 
    updateMember, 
    deleteMember, 
    setCurrentTree 
  } = useFamilyStore()
  
  const { isAuthenticated, user } = useAuthStore()

  const showModal = () => {
    setIsModalVisible(true)
  }

  const handleCancel = () => {
    setIsModalVisible(false)
    form.resetFields()
  }

  useEffect(() => {
    if (isAuthenticated) {
      fetchMembers()
      fetchTrees()
    }
  }, [isAuthenticated, fetchMembers, fetchTrees])
  
  const handleCreateMember = async (memberData: any) => {
    try {
      await createMember({
        ...memberData,
        gender: memberData.gender === '男' ? 'MALE' : 'FEMALE',
        generation: memberData.generation || 1,
        isAlive: memberData.isAlive !== false
      })
      message.success('成员添加成功')
      setIsModalVisible(false)
      // 如果有当前选中的树，刷新树结构
      if (currentTree) {
        fetchTreeStructure(currentTree.id)
      }
    } catch (error: any) {
      message.error(error.message || '添加成员失败')
    }
  }
  
  const handleUpdateMember = async (memberData: any) => {
    try {
      if (currentMember) {
        await updateMember(currentMember.id, {
          ...memberData,
          gender: memberData.gender === '男' ? 'MALE' : 'FEMALE'
        })
        message.success('成员更新成功')
        setEditModalVisible(false)
        setCurrentMember(null)
        // 如果有当前选中的树，刷新树结构
        if (currentTree) {
          fetchTreeStructure(currentTree.id)
        }
      }
    } catch (error: any) {
      message.error(error.message || '更新成员失败')
    }
  }
  
  const handleDeleteMember = async (memberId: number) => {
    try {
      await deleteMember(memberId)
      message.success('成员删除成功')
      // 如果有当前选中的树，刷新树结构
      if (currentTree) {
        fetchTreeStructure(currentTree.id)
      }
    } catch (error: any) {
      message.error(error.message || '删除成员失败')
    }
  }
  
  const handleTreeSelect = (tree: any) => {
    setCurrentTree(tree)
    fetchTreeStructure(tree.id)
  }
  
  const handleAddMember = (parentId?: number) => {
    setCurrentMember(null)
    setIsModalVisible(true)
  }
  
  const handleEditMember = (memberId: number) => {
    const member = members.find(m => m.id === memberId)
    if (member) {
      setCurrentMember(member)
      setEditModalVisible(true)
    }
  }
  
  const handleAddTree = async () => {
    try {
      // TODO: 实现创建族谱树的功能
      message.info('创建族谱树功能开发中')
    } catch (error: any) {
      message.error(error.message || '创建失败')
    }
  }

  const uploadProps = {
    name: 'avatar',
    action: '/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info: any) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`)
      }
    },
  }

  const uploadProps = {
    name: 'avatar',
    action: '/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info: any) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`)
      }
    },
  }

  return (
    <div>
      <Card
        title="族谱管理"
        extra={
          <div style={{ display: 'flex', gap: '8px' }}>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddTree}>
              创建族谱
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAddMember}>
              添加成员
            </Button>
          </div>
        }
        style={{ marginBottom: 16 }}
      >
        <Tabs activeKey={currentTab} onChange={setCurrentTab}>
          <Tabs.TabPane key="tree" tab="族谱视图">
            {trees.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <p style={{ color: '#999', marginBottom: '16px' }}>还没有创建族谱树</p>
                <Button type="primary" onClick={handleAddTree}>
                  创建第一个族谱树
                </Button>
              </div>
            ) : (
              <div style={{ marginBottom: '16px' }}>
                <div style={{ marginBottom: '16px' }}>
                  <Button.Group>
                    {trees.map(tree => (
                      <Button
                        key={tree.id}
                        type={currentTree?.id === tree.id ? 'primary' : 'default'}
                        onClick={() => handleTreeSelect(tree)}
                      >
                        {tree.name}
                      </Button>
                    ))}
                  </Button.Group>
                </div>
                
                {loading ? (
                  <div style={{ textAlign: 'center', padding: '40px' }}>加载中...</div>
                ) : (
                  <FamilyTreeView
                    tree={treeStructure}
                    onAddMember={handleAddMember}
                    onEditMember={handleEditMember}
                  />
                )}
              </div>
            )}
          </Tabs.TabPane>
          
          <Tabs.TabPane key="members" tab="成员列表">
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>加载中...</div>
            ) : members.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <p style={{ color: '#999', marginBottom: '16px' }}>还没有添加家族成员</p>
                <Button type="primary" onClick={handleAddMember}>
                  添加第一个成员
                </Button>
              </div>
            ) : (
              <div style={{ maxHeight: '600px', overflowY: 'auto' }}>
                {members.map(member => (
                  <Card key={member.id} style={{ marginBottom: '8px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                        <Avatar
                          src={member.avatar}
                          icon={<UserOutlined />}
                          style={{ backgroundColor: member.gender === 'MALE' ? '#1890ff' : '#ff4d4f' }}
                        />
                        <div>
                          <div style={{ fontWeight: 'bold' }}>{member.name}</div>
                          <div style={{ fontSize: '12px', color: '#999' }}>
                            第{member.generation}代 • {member.gender === 'MALE' ? '男性' : '女性'}
                          </div>
                        </div>
                      </div>
                      <div style={{ display: 'flex', gap: '8px' }}>
                        <Button
                          icon={<EditOutlined />}
                          onClick={() => handleEditMember(member.id)}
                        >
                          编辑
                        </Button>
                        <Button
                          icon={<DeleteOutlined />}
                          danger
                          onClick={() => handleDeleteMember(member.id)}
                        >
                          删除
                        </Button>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            )}
          </Tabs.TabPane>
        </Tabs>
      </Card>

      {/* 添加成员模态框 */}
      <Modal
        title="添加家族成员"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={600}
      >
        <FamilyMemberForm
          onSubmit={handleCreateMember}
          onCancel={() => setIsModalVisible(false)}
          loading={loading}
        />
      </Modal>

      {/* 编辑成员模态框 */}
      <Modal
        title="编辑家族成员"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false)
          setCurrentMember(null)
        }}
        footer={null}
        width={600}
      >
        <FamilyMemberForm
          member={currentMember}
          onSubmit={handleUpdateMember}
          onCancel={() => {
            setEditModalVisible(false)
            setCurrentMember(null)
          }}
          loading={loading}
        />
      </Modal>
    </div>
  )
}